#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Defines a file directory wrapper around the FileApp component from paste.


TODO:  normalize path sanely
TODO:  handle multiple default documents via argument
"""
from logging import debug
from os.path import abspath, isfile, join as filejoin, exists as fileexists
from paste.fileapp import FileApp
from tack.lib import not_found


def fileserver(dirname, handle404=not_found, fileapp=FileApp, basekey=None):
    """ Creates and returns an application for serving a directory of files.


    """
    appcache = {} 
    dirname = abspath(dirname)
    debug('created fileserver for dir:  %s', dirname)

    def server(env, respond):
        path = env['dispatcher.groups'][basekey] if basekey else env['PATH_INFO']
        path = path.replace('..', '').strip('/')
        filename = filejoin(dirname, path)
        indexname = filejoin(filename, 'index.html')
        debug('fileserver path: %s file: %s', path, filename)
        try:
            app = appcache[path]
        except (KeyError, ):
            if fileexists(indexname) and isfile(indexname):
                app = appcache[path] = fileapp(indexname)
            elif fileexists(filename) and isfile(filename):
                app = appcache[path] = fileapp(filename)
            else:
                app = handle404
        return app(env, respond)
    return server
